//-----------------------------------------------------------------------------
// Filename: LoginController.cs
//
// Description: Authentication controller for the SIP Switch.
//
// History:
// 02 Nov 2006	Aaron Clauson	Created.
//
// License: 
// Aaron Clauson.
//-----------------------------------------------------------------------------

using System;
using System.Collections;
using System.Configuration;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using MaverickLite.Security;
using BlueFace.Sys;
using log4net;

namespace SIPSwitch.Web
{
	public class LoginController : SecureXmlController
	{
		private new static ILog logger = AppState.GetLogger("sipswitch");

        private static string m_switchDBConnStr = ConfigurationManager.AppSettings["SIPSwitchDBConnStr"];
        private static string m_switchStorageTypeStr = ConfigurationManager.AppSettings["SIPSwitchDBType"];
        private static string m_switchServiceHostname = ConfigurationManager.AppSettings["SIPSwitchServiceHostname"];
		private StorageLayer m_sipSwitchStorageLayer = null;

        private SIPProxyWebServiceClient m_proxyInfoServiceProxy = new SIPProxyWebServiceClient();  // The proxy URL is initialised from the system.servicemodel element in the web.config file.

		public LoginController(XmlElement initParams) : base(initParams)
		{
            m_sipSwitchStorageLayer = new StorageLayer(StorageTypesConverter.GetStorageType(m_switchStorageTypeStr), m_switchDBConnStr);
		}

		protected override void InitialiseRequest(HttpContext context)
		{
			try
			{
				base.InitialiseRequest(context);

                Hashtable formData = MavRequestState.GetRequestData();
                string deleteAccount = formData["deleteaccount"] as string;

                if (this.m_authenticated && deleteAccount != null && deleteAccount.Trim().Length > 0)
                {
                    string username = this.m_authenticatedCredentials.Username;

                    logger.Debug("Deleting sipswitch account for " + username + ".");

                    string deleteDialplanSQL = "delete from dialplans where username = '" + username.Replace("'", "''") + "'";
                    logger.Debug(deleteDialplanSQL);
                    m_sipSwitchStorageLayer.ExecuteNonQuery(deleteDialplanSQL);

                    string deleteCustomerSQL = "delete from customers where username = '" + username.Replace("'", "''") + "'";
                    logger.Debug(deleteCustomerSQL);
                    m_sipSwitchStorageLayer.ExecuteNonQuery(deleteCustomerSQL);

                    string deleteLogMessagesSQL = "delete from switchlog where username = '" + username.Replace("'", "''") + "'";
                    logger.Debug(deleteLogMessagesSQL);
                    m_sipSwitchStorageLayer.ExecuteNonQuery(deleteLogMessagesSQL);

                    // Delete all the live registrations from the sipswitch proxy.
                    m_proxyInfoServiceProxy.DeleteAllUserSIPRegistrations(username);

                    this.m_pageModel.AddToModel("<page><identity/></page>", true);
                    this.m_view = "unauthenticated";
                }
                else if (this.m_authenticated)
                {                   
                    string username = this.m_authenticatedCredentials.Username;

                    logger.Debug("Getting sipswitch password for " + username + ".");
                    string sipSwitchPassword = m_sipSwitchStorageLayer.ExecuteScalar("select sippassword from sipaccounts where upper(sipusername) = '" + username.Replace("'", "''").ToUpper() + "'") as string;

                    this.m_pageModel.AddToModel("<page><sipswitchservicehostname>" + m_switchServiceHostname + "</sipswitchservicehostname><sipswitchpassword>" + sipSwitchPassword + "</sipswitchpassword></page>", true);

                    this.m_view = "authenticated";
                }
                else
                {
                    this.m_view = "unauthenticated";
                }
			}
			catch(Exception excp)
			{
				logger.Error("Exception SIPSwitchController. " + excp.Message);
				this.m_view = "unauthenticated";
			}
		}
	}
}
